<?php

switch($_GET['act'])
{
	case 'thankyou':
		$tpl = "thankyou";
		$title_page = THANK_YOU;
		break;
		
	case 'view':		
		global $title_bar;
		$title_bar = "Cart";
		$title_page = CART;
		$tpl = 'view';
		break;
		
	case 'add':
		AddCart();
		GetPreviousUrl();
		$tpl = 'view';
		$title_page = CART;
		break;	
	
	case 'update':
		UpdateCart();
		$tpl = 'view';
		$title_page = CART;
		break;
			
	case 'checkout':		
		global $info;
		$sql = "select content_vn, content_en from infos where name_vn like '%address ". $_SESSION['lg']."%'";    
    	$info = $db->getRow($sql);
		$tpl = 'checkout';
		$title_page = "Check out";
		break;	
		
	case 'ordersm':
		Ordersm();
		break;
		
	default:		
		global $title_bar;
		$title_bar = "Cart";
		$tpl = 'view';
		break;
}

function GetPreviousUrl()
{
	global $db, $FullUrl, $prefix_url;	
	global $page, $plpage, $set_per_page, $c, $title_bar;
	
	$id = isset($_GET['id'])?$_GET['id']:0;
	if(is_numeric($id))
	{
		$sql = "select cid from products where id = " . $id;	
		$r = $db->getRow($sql);
		
		$url = GetCategoryProduct($r, $_SESSION['lg']);
		
		$_SESSION['CONTINUE_SHOPPING_URL'] = $url;
	}
}

function AddCart()
{
	if(!isset($_SESSION['gids'])){
		$_SESSION['gids'] = array();
		$_SESSION['counts'] = array();
	}
	$str = CleanSQLInjection(trim(isset($_GET['id'])?$_GET['id']:''));
	$sl = CleanSQLInjection((isset($_GET['sl'])&&is_numeric($_GET['sl']))?$_GET['sl']:0);
	
	for($i=0;$i<count($_SESSION['gids']);$i++){
		$sl = ($sl<=CST_LIMIT_CART_NUMBER&&$sl>0?$sl:1);
		
		if($_SESSION['gids'][$i] == $str){
			$_SESSION['counts'][$i]+= $sl;
			break;
		}
	}
	
	if($i==count($_SESSION['gids'])){
		$_SESSION['gids'][] = $str;
		$sl = (($sl<=CST_LIMIT_CART_NUMBER&&$sl>0)?$sl:1);
		$_SESSION['counts'][$i] = $_SESSION['counts'][$i]<CST_LIMIT_CART_NUMBER&&$_SESSION['counts'][$i]>0?$_SESSION['counts'][$i]:$sl;
	}
	
	global $title_bar;
	$title_bar = "Cart";
}
function UpdateCart()
{
	$add   = isset($_POST["item"])  ? $_POST["item"]  : 0;
	$qt   = isset($_POST["qt"])  ? $_POST["qt"]  : 0;
	$remove = $_POST['remove'];	
	$ngids = array();
	$ncounts = array();
	for($i=0;$i<count($add);$i++)
	{		
		$qt[$i] = $qt[$i]<=CST_LIMIT_CART_NUMBER&&$qt[$i]>0?$qt[$i]:1;
		$ngids[$i] = $add[$i];		
		$ncounts[$i] = $qt[$i];		
	}
		
	for ($j=0;$j<count($remove);$j++)	
	{	
		$i=0;
		while ($i<count($ngids) && $ngids[$i] != $remove[$j]) 
			$i++;
		if ($i<count($ngids)) 
		{
			array_splice($ngids,$i,1);
			array_splice($ncounts,$i,1);
		}
	}
	
	$_SESSION["gids"] = $ngids;
	$_SESSION["counts"] = $ncounts;
		
	if (isset($order_step)) {
		unset($_SESSION["order_step"]);
		unset($order_step);
	}
	global $title_bar;
	$title_bar = "Cart";
}

function Ordersm()
{
	include("./includes/mail_config.php");
	global $db, $mail, $OrderId, $FullUrl;
	
	$sql = "select content_vn, content_en from infos where name_vn like '%contact mail%'";

	$r = $db->getRow($sql);
	
	$mailTemplatePath = './EmailTemplate/ConfirmOrder' .'_' . $_SESSION['lg'] . '.html';
	
	$fh = fopen($mailTemplatePath, 'r');
		
	$template = fread($fh, filesize($mailTemplatePath));
	
	fclose($fh);
	
	$name = SafeFormValue('HoTenInput');
	$company = SafeFormValue('CongTyInput');
	$address = SafeFormValue('DiaChiInput');
	$phone = SafeFormValue('DienThoaiInput');
	$email = SafeFormValue('EmailInput');
	$content = SafeFormValue('TinNhanInput');
	
	$receive_name = SafeFormValue('receive_HoTenInput');
	$receive_company = SafeFormValue('receive_CongTyInput');
	$receive_address = SafeFormValue('receive_DiaChiInput');
	$receive_phone = SafeFormValue('receive_DienThoaiInput');
	$receive_email = SafeFormValue('receive_EmailInput');
	
	if(isset($_SESSION['gids']))
	{
		if(isset($_SESSION['member_id']))
			$arr['odr_mem_id'] = $_SESSION['member_id'];
		$arr['odr_shipping_name'] = $receive_name;
		$arr['odr_shipping_phone'] = $receive_phone;
		$arr['odr_shipping_email'] = $receive_email;
		$arr['odr_shipping_address'] = $receive_address;
		$arr['odr_shipping_company'] = $receive_company;
		$arr['odr_payment_name'] = $name;
		$arr['odr_payment_phone'] = $phone;
		$arr['odr_payment_email'] = $email;
		$arr['odr_payment_address'] = $address;
		$arr['odr_payment_company'] = $company;
		$arr['odr_last_update_date'] = getdate();
	
		$idorder = vaInsert('orders',$arr);
		
		$_SESSION['code'] = $idorder;
	}
	
	$mail_to = strip_tags($r['content_vn']);

  	$mail_subject = "Như Quỳnh $idorder - ".$name;

	$total = 0;

	for($i=0;$i<count($_SESSION['gids']);$i++){

		$sql = "select price, code, name_vn, name_en from products where id=".$_SESSION['gids'][$i];

		$r = $db->getRow($sql);

		$tien = $_SESSION['counts'][$i]*$r['price'];

		$total += $tien;
		
		$order_detail .= "<tr><td align='center'>".($i+1)."</td><td>".$r['code']."</td><td>".$r['name_'.$_SESSION['lg']]."</td><td>".number_format($r['price']).CST_CURRENCY_CODE."</td><td align='center'>".$_SESSION['counts'][$i]."</td><td>".number_format($tien).CST_CURRENCY_CODE."</td></tr>";
		
		$arr = array();
		$arr['od_odr_id'] = $idorder;
		$arr['od_pro_id'] = $_SESSION['gids'][$i];
		$arr['od_pro_quantity'] = $_SESSION['counts'][$i];
		
		vaInsert('order_detail', $arr);
	}
	
	$template = str_replace('[NAME]', $name, $template);
	$template = str_replace('[COMPANY]', $company, $template);
	$template = str_replace('[ORDER_DETAIL]', $order_detail, $template);
	$template = str_replace('[TOTAL]', number_format($total), $template);
	$template = str_replace('[ADDRESS]', $address, $template);
	$template = str_replace('[PHONE]', $phone, $template);
	$template = str_replace('[IDORDER]', $idorder, $template);
	$template = str_replace('[CONTENT]', $content, $template);
	$template = str_replace('[CURRENCY_CODE]', CST_CURRENCY_CODE, $template);
	$template = str_replace('[EMAIL]', $email, $template);
	
	$template = str_replace('[RECEIVE_NAME]', $receive_name, $template);
	$template = str_replace('[RECEIVE_COMPANY]', $receive_company, $template);
	$template = str_replace('[RECEIVE_ADDRESS]', $receive_address, $template);
	$template = str_replace('[RECEIVE_PHONE]', $receive_phone, $template);
	$template = str_replace('[RECEIVE_EMAIL]', $receive_email, $template);
	
	$_SESSION['cost'] = $total;
	$mail->Subject = $mail_subject;

	$mail->MsgHTML($template);
	
	$sql = "select content_vn, content_en from infos where name_vn like '%mail sender name%'";

	$r = $db->getRow($sql);
	
	$mail->AddAddress($mail_to, $r['content_vn']?$r['content_vn']:'Webmaster');
	
	$mail->AddBCC($email, $r['content_vn']?$r['content_vn']:'Webmaster');
	
	$page = $FullUrl . '/thank-you.html';
	
	if(isset($_SESSION['gids']))
	{
		if(!$mail->Send()) {
			$_SESSION['mess'] = SEND_EMAIL_UNSUCCESSFULLY_MESS;
			$page = $FullUrl . '/index.html';
		} else {
			$_SESSION['mess'] = SEND_CART_VIA_EMAIL_SUCCESSFULLY_MESS;
		}
	}
	

	unset($_SESSION['gids']);

	unset($_SESSION['counts']);
	
	unset($_SESSION['CONTINUE_SHOPPING_URL']);
	
	page_transfer2($page);
}

?>